﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using ModeloGaleriaNET;
using System.Data.Objects;
using System.ComponentModel;
using CADs;
using Xceed.Wpf.Toolkit;

namespace GaleriaNET
{
    /// <summary>
    /// Lógica de interacción para SubastaFilterWindow.xaml
    /// </summary>
    public partial class SubastaFilterWindow : Window
    {
        private bool loaded;
        private List<SubastaFilter> filters;
        private bool success;
        private BackgroundWorker worker;
        private dynamic tematicas;

        public SubastaFilterWindow()
        {
            InitializeComponent();
            loaded = false;
            filters = new List<SubastaFilter>();
            worker = new BackgroundWorker();
            worker.DoWork += worker_DoWork;
            worker.RunWorkerCompleted += worker_RunWorkerCompleted;
        }

        public bool Success
        {
            get { return success; }
        }

        public List<SubastaFilter> Filters
        {
            get { return filters; }
        }

        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            tematicas = new TematicaCAD().GetTematicaIdNombre();
        }

        private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (tematicas != null)
            {
                clbTematicas.ItemsSource = tematicas;
                clbTematicas.DisplayMemberPath = "Nombre";
                clbTematicas.ValueMemberPath = "Id";
                clbTematicas.SelectedMemberPath = "Id";
                tematicas = null;
            }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            if (!loaded)
            {
                if (!worker.IsBusy)
                    worker.RunWorkerAsync();
                dtFechaLimite.SelectedDateFormat = DatePickerFormat.Short;
                loaded = true;
            }
        }

        private void btCancelar_Click(object sender, RoutedEventArgs e)
        {
            success = false;
            Close();
        }

        private void btAcepar_Click(object sender, RoutedEventArgs e)
        {
            SubastaFilter filtro = null;
            string anyo;
            int numAnyo;
            string tematicas = string.Empty;

            #region Referencia externa
            if (!string.IsNullOrEmpty(tbRefExterna.Text))
            {
                filtro = new SubastaFilter(@"ToLower(it.referenciaExterna) like '%' + @refInput + '%'");
                filtro.Parameters.Add(new ObjectParameter("refInput", tbRefExterna.Text.ToLower()));
                filters.Add(filtro);
            }
            #endregion
            #region Nombre de la obra
            if (!string.IsNullOrEmpty(tbNombreObra.Text))
            {
                filtro = new SubastaFilter(@"ToLower(it.nombreObra) like '%' + @nombreObraInput + '%'");
                filtro.Parameters.Add(new ObjectParameter("nombreObraInput", tbNombreObra.Text.ToLower()));
                filters.Add(filtro);
            }
            #endregion
            #region Autor de la obra
            if (!string.IsNullOrEmpty(tbAutorObra.Text))
            {
                filtro = new SubastaFilter(@"ToLower(it.autorObra) like '%' + @autorObraInput + '%'");
                filtro.Parameters.Add(new ObjectParameter("autorObraInput", tbAutorObra.Text.ToLower()));
                filters.Add(filtro);
            }
            #endregion
            #region Estado de la obra
            if (cbEstadoObra.SelectedIndex != -1)
            {
                filtro = new SubastaFilter(@"it.estadoObra = @estadoInput");
                switch (cbEstadoObra.SelectedIndex)
                {
                    case 0:
                        filtro.Parameters.Add(new ObjectParameter("estadoInput", "original"));
                        break;
                    case 1:
                        filtro.Parameters.Add(new ObjectParameter("estadoInput", "deteriorado"));
                        break;
                    case 2:
                        filtro.Parameters.Add(new ObjectParameter("estadoInput", "restaurado"));
                        break;
                }
                filters.Add(filtro);
            }
            #endregion
            #region Año de la obra
            if (!string.IsNullOrWhiteSpace(tbAnyo.Text))
            {
                try
                {
                    anyo = tbAnyo.Text.Replace(" ", "");
                    numAnyo = cbAntesCristo.SelectedIndex == 0 ? Convert.ToInt32(anyo) : Convert.ToInt32(anyo) * -1;

                    switch (cbFiltroAnyo.SelectedIndex)
                    {
                        case 0:
                            filtro = new SubastaFilter(@"it.anyoObra = @anyoInput");
                            break;
                        case 1:
                            filtro = new SubastaFilter(@"it.anyoObra < @anyoInput");
                            break;
                        case 2:
                            filtro = new SubastaFilter(@"it.anyoObra > @anyoInput");
                            break;
                    }
                    filtro.Parameters.Add(new ObjectParameter("anyoInput", numAnyo));
                    filters.Add(filtro);
                }
                catch (Exception)
                {
                }
            }
            #endregion
            #region Fecha límite
            if (dtFechaLimite.SelectedDate != null)
            {
                switch (cbFiltroFecha.SelectedIndex)
                {
                    case 0:
                        filtro = new SubastaFilter(@"it.fechaLimite >= @inputDate and it.fechaLimite < @inputDateNextDay");
                        filtro.Parameters.Add(new ObjectParameter("inputDate", ((DateTime)dtFechaLimite.SelectedDate).Date));
                        filtro.Parameters.Add(new ObjectParameter("inputDateNextDay", ((DateTime)dtFechaLimite.SelectedDate).AddDays(1).Date));
                        break;
                    case 1:
                        filtro = new SubastaFilter(@"it.fechaLimite < @inputDate");
                        filtro.Parameters.Add(new ObjectParameter("inputDate", ((DateTime)dtFechaLimite.SelectedDate.Value).Date));
                        break;
                    case 2:
                        filtro = new SubastaFilter(@"it.fechaLimite > @inputDate");
                        filtro.Parameters.Add(new ObjectParameter("inputDate", ((DateTime)dtFechaLimite.SelectedDate.Value).Date));
                        break;
                }
                filters.Add(filtro);
            }
            #endregion
            #region Número de pujas
            if (cbMaxPujas.SelectedIndex != -1)
            {
                switch (cbMaxPujas.SelectedIndex)
                {
                    case 0:
                        filtro = new SubastaFilter(@"it.maximoPujasPostor = @mppInput");
                        filtro.Parameters.Add(new ObjectParameter("mppInput", Int32.MaxValue));
                        break;
                    case 1:
                        filtro = new SubastaFilter(@"it.maximoPujasPostor = @mppInput");
                        filtro.Parameters.Add(new ObjectParameter("mppInput", Convert.ToInt32(iudMaxPujas.Value)));
                        break;
                    case 2:
                        filtro = new SubastaFilter(@"it.maximoPujasPostor > @mppInput");
                        filtro.Parameters.Add(new ObjectParameter("mppInput", Convert.ToInt32(iudMaxPujas.Value)));
                        break;
                    case 3:
                        filtro = new SubastaFilter(@"it.maximoPujasPostor < @mppInput");
                        filtro.Parameters.Add(new ObjectParameter("mppInput", Convert.ToInt32(iudMaxPujas.Value)));
                        break;
                }
                filters.Add(filtro);
            }
            #endregion
            #region Estado subasta
            if (cbEstadoSubasta.SelectedIndex != -1)
            {
                filtro = new SubastaFilter(@"EXISTS (select shs.estado from subastashaveestadossubasta as " +
                        @"shs where it.id = shs.subasta and shs.fechafin is null and shs.estado = @inputEstado)", null);
                filtro.Parameters.Add(new ObjectParameter("inputEstado", cbEstadoSubasta.SelectedIndex + 1));
                filters.Add(filtro);
            }
            #endregion
            #region Temática
            if (clbTematicas.SelectedItems.Count > 0)
            {
                foreach (object item in clbTematicas.SelectedItems)
                {
                    if (string.IsNullOrWhiteSpace(tematicas))
                        tematicas = Convert.ToString(item.GetType().GetProperty("Id").GetValue(item, null));
                    else
                        tematicas += "," + Convert.ToString(item.GetType().GetProperty("Id").GetValue(item, null));
                }

                if (cbBusqueda.IsChecked == false) // Alguna de las seleccionadas
                    filtro = new SubastaFilter(@"EXISTS (select t.id from it.tematicas as t where t.id in {" + tematicas + "})");
                else if (cbBusqueda.IsChecked == true) // Exactamente las seleccionadas
                {
                    filtro = new SubastaFilter(@"count(select value t.id from it.tematicas as t where t.id in {" + tematicas + "}) = @inputTam");
                    filtro.Parameters.Add(new ObjectParameter("inputTam", clbTematicas.SelectedItems.Count));
                }
                
                filters.Add(filtro);
            }
            #endregion
            #region Negociado
            if (cbNegociado.SelectedIndex != -1)
            {
                if (cbNegociado.SelectedIndex == 0) // Manual
                    filtro = new SubastaFilter("it.tipoNegociado = 'manual'");
                else // Automático
                    filtro = new SubastaFilter("it.tipoNegociado = 'automatico'");
                filters.Add(filtro);
            }
            #endregion
            #region Origen (Propia o de otro)
            if (cbOrigen.SelectedIndex != -1)
            {
                if (cbOrigen.SelectedIndex == 0) // Creadas en la galería
                    filtro = new SubastaFilter("it IS NOT OF (ModeloGaleriaNET.SubastaDeOtro)");
                else // Suscritas desde fuera
                    filtro = new SubastaFilter("it IS OF (ModeloGaleriaNET.SubastaDeOtro)", null);

                filters.Add(filtro);
            }
            #endregion
            success = true;
            Close();
        }
    }
}
